package com.sdx.console.chart.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.common.utils.Utils;
import com.sdx.console.common.entity.BaseProvince;
import com.sdx.console.saas.entity.SaasTenant;
import com.sdx.console.utils.BigDecimalUntil;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName CustomerChartController
 * @Description
 * @Author kangbin
 * @Date 2019/12/4 14:57
 */
@Controller
@RequestMapping("/chart/trans")
public class TransChartController extends AuthorizedBaesController {

    private static final Logger log = LoggerFactory.getLogger(TransChartController.class);
    private static final String MODEL = "/chart/trans";
    private static final String SQL = "chart.trans";

    @Resource
    private SQLManager sqlManager;

    private void setPageParam(ModelAndView view, HttpServletRequest request) {

    }

    @GetMapping("/index.do")
    @Function("chart.trans.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/transIndex.html") ;
        setPageParam(view,request);
        return view;
    }


    @PostMapping("/histogram.json")
    @Function("chart.trans.query")
    @ResponseBody
    public JsonResult histogram(String dateTime) {

        JsonResult result = JsonResult.success();
        String startTime = null;
        String endTime = null;
        if(StringUtils.isNotEmpty(dateTime)){
            String[] timePairs = dateTime.split(" ~ ");
            String startStr = timePairs[0];
            startTime = startStr;
            String endStr = timePairs[1] ;
            endTime = endStr;

        }else{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            Calendar  calendar   =   new   GregorianCalendar();
            calendar.setTime(date);
            calendar.add(calendar.DATE,-7);
            startTime = sdf.format(calendar.getTime());
            endTime = sdf.format(date);
        }

//        if(StringUtils.isEmpty(dateTime)){
//            SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
//            dateTime = sdf.format(new Date());
//        }
        Map<String,Object> param = new HashMap<>();
        param.put("startTime",startTime);
        param.put("endTime",endTime);

        JSONArray array = new JSONArray();
        JSONObject json = new JSONObject();

        //已支付订单数
        List<Integer> payList = sqlManager.select(SQL + ".queryPayCount", Integer.class, param);
        Integer[] pay = newArray(Integer[].class,payList);
        json.put("name","已支付");
        json.put("data",pay);
        array.add(json);

        //未支付订单数
        List<Integer> unpaidList = sqlManager.select(SQL + ".queryUnpaidCount", Integer.class, param);
        Integer[] unpaid = newArray(Integer[].class,unpaidList);
        json = new JSONObject();
        json.put("name","未支付");
        json.put("data",unpaid);
        array.add(json);

        //省份信息
        List<String> provList = sqlManager.select(SQL + ".queryProv", String.class, param);
        String[] prov = newArray(String[].class,provList);
        JSONObject data = new JSONObject();
        data.put("prov",prov);
        data.put("series",array);
        data.put("dateTime",startTime+" ~ "+endTime);
        result.setData(data);
        return result;
    }

    public <T> T[] newArray(Class<? extends T[]> newType,List<T> list){
        T[] object = (T[]) Array.newInstance(newType.getComponentType(),list.size());
        list.toArray(object);
        return object;
    }

    @GetMapping("/custIndex.do")
    @ResponseBody
    public ModelAndView custIndex(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/custIndex.html") ;
        setPageParam(view,request);
        return view;
    }

    @PostMapping("/cutsCharts.json")
    @ResponseBody
    public JsonResult cutsCharts(String dateTime) {
        JsonResult result = JsonResult.success();
        String startTime = null;
        String endTime = null;
        if(StringUtils.isNotEmpty(dateTime)){
            String[] timePairs = dateTime.split(" ~ ");
            String startStr = timePairs[0] + " 00:00:00";
            startTime = startStr;
            String endStr = timePairs[1] + " 23:59:59";
            endTime = endStr;

        }else{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            Calendar  calendar   =   new   GregorianCalendar();
            calendar.setTime(date);
            calendar.add(calendar.DATE,-7);
            startTime = sdf.format(calendar.getTime()) + " 00:00:00";
            endTime = sdf.format(date)  + " 23:59:59";
        }
        Map<String,Object> param = new HashMap<>();
        param.put("startTime",startTime);
        param.put("endTime",endTime);


        JSONArray array = new JSONArray();
        List<String> dateList = new ArrayList<>();
        List<String> totalList = new ArrayList<>();
        List<Map> payList = sqlManager.select(SQL + ".queryCustCount", Map.class, param);
        for (Map<String,String> map : payList) {
            dateList.add(map.get("date"));
            totalList.add(map.get("total"));
        }

        JSONObject object = new JSONObject();
//        String[] unpaid = newArray(String[].class,totalList);

        Object[] objects = totalList.toArray();
        object.put("name","用户注册");
        object.put("data",objects);
        array.add(object);
        JSONObject json = new JSONObject();
        json.put("categories",dateList.toArray());
        json.put("series",array);
        result.setData(json);
        return result;
    }

    @GetMapping("/orderIndex.do")
    @ResponseBody
    public ModelAndView orderIndex(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/orderIndex.html") ;
        setPageParam(view,request);
        return view;
    }

    @PostMapping("/orderCharts.json")
    @ResponseBody
    public JsonResult orderCharts(String dateTime) {
        JsonResult result = JsonResult.success();
        String startTime = null;
        String endTime = null;
        if(StringUtils.isNotEmpty(dateTime)){
            String[] timePairs = dateTime.split(" ~ ");
            String startStr = timePairs[0];
            startTime = startStr;
            String endStr = timePairs[1] ;
            endTime = endStr;

        }else{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            Calendar  calendar   =   new   GregorianCalendar();
            calendar.setTime(date);
            calendar.add(calendar.DATE,-7);
            startTime = sdf.format(calendar.getTime());
            endTime = sdf.format(date);
        }
        Map<String,Object> param = new HashMap<>();
        param.put("startTime",startTime);
        param.put("endTime",endTime);


        JSONArray array = new JSONArray();
        List<String> dateList = new ArrayList<>();
        List<String> totalList = new ArrayList<>();
        List<Map> payList = sqlManager.select(SQL + ".queryOrderCount", Map.class, param);
        for (Map<String,String> map : payList) {
            dateList.add(map.get("payDate"));
            totalList.add(map.get("total"));
        }

        JSONObject object = new JSONObject();
//        String[] unpaid = newArray(String[].class,totalList);

        Object[] objects = totalList.toArray();
        object.put("name","订单");
        object.put("data",objects);
        array.add(object);
        JSONObject json = new JSONObject();
        json.put("categories",dateList.toArray());
        json.put("series",array);
        result.setData(json);
        return result;
    }

    @GetMapping("/moneyIndex.do")
    @ResponseBody
    public ModelAndView moneyIndex(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/moneyIndex.html") ;
        setPageParam(view,request);
        return view;
    }

    @PostMapping("/moneyCharts.json")
    @ResponseBody
    public JsonResult moneyCharts(String dateTime) {
        JsonResult result = JsonResult.success();
        String startTime = null;
        String endTime = null;
        if(StringUtils.isNotEmpty(dateTime)){
            String[] timePairs = dateTime.split(" ~ ");
            String startStr = timePairs[0];
            startTime = startStr;
            String endStr = timePairs[1] ;
            endTime = endStr;

        }else{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            Calendar  calendar   =   new   GregorianCalendar();
            calendar.setTime(date);
            calendar.add(calendar.DATE,-7);
            startTime = sdf.format(calendar.getTime());
            endTime = sdf.format(date);
        }
        Map<String,Object> param = new HashMap<>();
        param.put("startTime",startTime);
        param.put("endTime",endTime);


        JSONArray array = new JSONArray();
        List<String> dateList = new ArrayList<>();
        List<Float> totalList = new ArrayList<>();
        List<JSONObject> payList = sqlManager.select(SQL + ".queryOrderCount", JSONObject.class, param);
        for (JSONObject map : payList) {
            dateList.add(map.getString("payDate"));
            BigDecimal num1 = new BigDecimal( Float.parseFloat(map.getString("totalMoney")));
            BigDecimal num2 = new BigDecimal(100F);
            totalList.add(num1.divide(num2,2,BigDecimal.ROUND_HALF_UP).floatValue());
        }

        JSONObject object = new JSONObject();
        Object[] objects = totalList.toArray();
        object.put("name","收入");
        object.put("data",objects);
        array.add(object);
        JSONObject json = new JSONObject();
        json.put("categories",dateList.toArray());
        json.put("series",array);
        result.setData(json);
        return result;
    }



}
